"use strict";

const os = require("os");
const fs = require("fs");
const fse = require("fs-extra");

/**
 * 获取请求服务机器的ip
 * @function getRemoteIP
 * @param {Object} req
 * @return {String}
 */
exports.getRemoteIP = req => {
  return (
    req.headers["x-forwarded-for"] ||
    (req.connection && req.connection.remoteAddress) ||
    (req.socket && req.socket.remoteAddress) ||
    (req.connection &&
      req.connection.socket &&
      req.connection.socket.remoteAddress) ||
    ""
  );
};

/**
 * 获取本地服务器ip
 * @function getLocalIP
 * @return {String} localIP
 */
exports.getLocalIP = () => {
  const interfaces = os.networkInterfaces();
  let localIP = "";
  Object.keys(interfaces).forEach(function(name) {
    interfaces[name].forEach(function(f) {
      if ("IPv4" !== f.family || f.internal !== false) {
        return;
      }
      localIP += f.address + ";";
    });
  });
  return localIP;
};

/**
 * @function streamTranser
 * @param {Object} file
 * @returns {*}
 */
exports.streamTranser = file => {
  return new Promise((resolve, reject) => {
    const { path, name } = file;
    if (fs.existsSync(name)) {
      fs.unlinkSync(name);
    }
    fse.ensureFile(name, function(err) {
      if (err) return reject(err);
      let stream = fs.createReadStream(path);
      let output = fs.createWriteStream(name);
      stream.pipe(output);
      resolve(true);
    });
  });
};

/**
 * 检验请求参数是否是后端要求的参数
 * @function reqVerify
 * @param {Object} body 前端请求参数
 * @param {Function} schema 后端要求参数<netSchema中定义>
 * @return {Boolean}
 */
exports.reqVerify = (body, schema) => {
  if (!body || !schema) return false;
  const validateResult = schema.validate(body, { allowUnknown: true });
  if (validateResult.error) {
    return false;
  } else {
    return validateResult.value || {};
  }
};

exports.mongoToObject = body => {
  if (!body) return {};
  return body.toObject ? body.toObject() : body;
};
